<template>
  <div class="dialogProduct" style="display: inline-block;margin-right: 10px;">
    <el-button size="small" @click="openDialong">添加产品</el-button>
    <el-dialog  :visible.sync="dialogVisible"
               width="800px"  center title="添加产品"
               :before-close="handleClose">
      <div>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid_item">
              <span class="label_item">产品名称：</span>
              <el-input size="small" v-model="productName" style="width: 270px"></el-input>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid_item">
              <span class="label_item">产品型号：</span>
              <el-input size="small" style="width: 270px" v-model="productNum"></el-input>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid_item">
              <span class="label_item">产品类型：</span>
              <el-select v-model="productType" clearable placeholder="请选择" size="small" style="width: 270px">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.dictKey"
                  :label="item.dictValue"
                  :value="item.dictKey">
                </el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid_item">
              <span class="label_item">产品分组：</span>
              <el-cascader :options="groupOptions" :props="treeProps" :show-all-levels="false" v-model="groupId"
                           size="small" style="width:270px" @change="changeGroup"></el-cascader>
            </div>
          </el-col>
        </el-row>
        <div style="text-align: center;margin-top: 10px">
          <el-button size="small" @click="reset" type="primary">重 置</el-button>
          <el-button size="small" type="primary" @click="search" :loading="loading">{{loading?'搜索中':'搜 索'}}</el-button>
        </div>
      </div>
      <div>
        <el-row>
          <el-col :span="12">
            <div class="grid_item">
              <p class="grid_title">筛选结果：</p>
              <div class="grid_content">
                <div class="group">
                  <el-checkbox-group v-model="productList">
                    <div class="product_item" v-for="(item,index) in checkoutList" :key="index">
                      <el-checkbox :label="item">{{item.name}}
                      </el-checkbox>
                      <div class="item-right">
                        <img :src="item.defaultPicUrl" class="product_img"/>
                        <div class="right-detail">
                          <p class="item_title moreTwo">{{item.productEname}}</p>
                          <p class="item_message more">{{item.productSpec.unitPriceCurrencyName}}
                            {{item.productSpec.unitPrice}}</p>
                        </div>
                      </div>
                    </div>
                  </el-checkbox-group>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid_item">
              <p class="grid_title">已选择：</p>
              <div class="grid_content">
                <div>
                  <div class="product_item" v-for="(item,index) in productList" :key="index">
                    <div class="item-right">
                      <img :src="item.defaultPicUrl" class="product_img"/>
                      <div class="right-detail">
                        <p class="item_title moreTwo">{{item.productEname}}</p>
                        <p class="item_message more">{{item.productSpec.unitPriceCurrencyName}}
                          {{item.productSpec.unitPrice}}</p>
                        <span class="icon-delete_icon remove_btn" @click="remove(item)"></span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose" size="small">取 消</el-button>
        <el-button type="primary" @click="submit" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
    import {getDictory} from '@/util/util'
    import {getleftMenu} from '@/api/product'
    import {queryProduct} from '@/api/order'
    import {getRateList} from '@/api/system/rate'
    import {mapState} from 'vuex'

    export default {
        name: "addProduct",
        props: ['orderId', 'custId', 'linkerIds', 'rate'],
        data() {
            return {
                dialogVisible: false,
                productType: '', // 产品类型
                typeOptions: [], // 类型集合
                groupOptions: [], // 产品分组集合
                treeProps: {
                    checkStrictly: true,
                    value: 'id',             // ID字段名
                    label: 'text',         // 显示名称
                    children: 'children'    // 子级字段名
                },
                checkoutList: [], // 搜索出的结果
                productName: '', // 产品名称
                productNum: '', // 产品型号
                typeId: '', // 产品分组,
                productList: [], // 选中的结果
                productPrice: 0, // 产品总金额
                currencyOptions: '', // 汇率集合
                loading: false,
                groupId: []
            }
        },
        computed: {
            ...mapState(['common']),
        },
        created() {
            this.typeOptions = getDictory('product_type').children;
            getleftMenu().then(res => {
                this.groupOptions = res.data.data
            })
        },
        mounted() {
            getRateList().then(res => {
                this.currencyOptions = res.data.data
            })

            document.body.addEventListener('click', () => {
                this.bus.$emit('closeMenu')
            })
        },
        methods: {
            handleClose() {
                this.productName = ''
                this.productNum = ''
                this.productType = ''
                this.typeId = ''
                this.checkoutList = []
                this.checkList = []
                this.dialogVisible = false
                this.productList = []
                this.groupId = []
            },
            openDialong() { // 打开弹窗
                this.dialogVisible = true
            },
            changeGroup(value) {
                this.typeId = value[value.length - 1]
            },
            search() {
                this.loading = true;
                queryProduct(this.productName, this.productNum, this.productType, this.typeId).then(res => {
                    this.loading = false;
                    let result = res.data.data;
                    if (result.length > 0) {
                        result.forEach(value => {
                            value.defaultPicUrl = value.defaultPicUrl.replace(/&amp;/g, '&')
                        })
                        this.checkoutList = result
                    } else {
                        this.$message({
                            message: '未查询到产品信息，请先添加产品',
                            type: 'success'
                        });
                    }
                }).catch(err => {
                    this.loading = false;
                })
            },
            remove(item) {
                this.productList.forEach((value, index) => {
                    if (item.id == value.id) {
                        this.productList.splice(index, 1)
                    }
                })
            },
            reset() { // 重置
                this.productName = ''
                this.productNum = ''
                this.productType = ''
                this.typeId = ''
                this.checkoutList = []
                this.checkList = []
                this.productList = []
                this.groupId = []
            },
            submit() {
                /**
                 * 产品Id:id
                 * 英文名：productEname
                 *产品编号：productCode
                 *产品图片：defaultPicUrl
                 *产品类型：productType
                 *含税成本价：productSpec.costPrice
                 *离岸价：productSpec.offshorePrice
                 *单价： productSpec.unitPrice
                 *毛利润率：grossMargin (单价 - 含税成本价) / 单价
                 *数量： prductCount 默认为1
                 * 其他费用： otherFee 默认为0
                 * 计量单位：productUnit
                 *包装单位：packingUnit
                 * 包装单位中文名： packingUnitName
                 *包装产品数：productSpec.packageNumber 默认为1
                 *包装体积： volumeNum productSpec.packageVolume(单位)
                 *包装体积小计：(数量/每包装产品数) * 包装体积 packagingVolumeSubtotal
                 * 包装毛重： productSpec.packagingGrossWeight
                 * 包装毛重小计：packagingGrossWeightSubTotal(数量/每包装产品数) * 包装毛重
                 *金额小计： amount 单价*数量+其他费用
                 * **/

                let newArr = []
                this.productList.forEach((value) => {
                    var productObj = {}
                    this.currencyOptions.forEach(item => {
                        if (value.productSpec.costCurrencyUnitName == item.currencyEname) {
                            productObj.costPrice = ((value.productSpec.costPrice * item.rateValue / this.rate).toFixed(2))
                        }
                        if (value.productSpec.offshoreCurrencyUnitName == item.currencyEname) {
                            productObj.offshorePrice = (value.productSpec.offshorePrice * item.rateValue / this.rate).toFixed(2)
                        }
                        if (value.productSpec.unitPriceCurrencyName == item.currencyEname) {
                            productObj.unitPrice = (value.productSpec.unitPrice * item.rateValue / this.rate).toFixed(2)
                        }
                    })
                    productObj.id = value.id
                    productObj.productEname = value.productEname
                    productObj.productCode = value.productCode
                    productObj.defaultPicUrl = value.defaultPicUrl
                    productObj.productType = value.productType
                    productObj.productTypeName = value.productTypeName
                    productObj.grossMargin = ((productObj.unitPrice - productObj.costPrice) / productObj.unitPrice).toFixed(2)
                    productObj.prductCount = 1
                    productObj.otherFee = 0
                    productObj.productUnit = value.productUnit
                    productObj.productUnitName = value.productUnitName
                    productObj.packingUnit = value.productSpec.packingUnit
                    productObj.packingUnitName = value.productSpec.packingUnitName
                    productObj.packageNumber = value.productSpec.packageNumber ? value.productSpec.packageNumber : 1
                    productObj.volumeNum = value.productSpec.packageVolume
                    productObj.packagingVolumeSubtotal = Math.ceil(productObj.prductCount / productObj.packageNumber) * productObj.volumeNum
                    productObj.packagingGrossWeight = value.productSpec.packagingGrossWeight
                    productObj.packagingGrossWeightSubTotal = Math.ceil(productObj.prductCount / productObj.packageNumber) * productObj.packagingGrossWeight
                    productObj.amount = productObj.unitPrice * productObj.prductCount + productObj.otherFee
                    console.log(productObj.unitPrice, productObj.prductCount)
                    newArr.push(productObj)
                })
                this.$emit('updateOrder', newArr)
                this.productName = ''
                this.productNum = ''
                this.productType = ''
                this.typeId = ''
                this.checkoutList = []
                this.checkList = []
                this.productList = []
                this.groupId = []
                this.dialogVisible = false
            }
        }
    }
</script>

<style lang="scss">
  .group {
    .el-checkbox-group {
      font-size: 13px !important;
    }
  }
</style>

<style scoped lang="scss">
  @import "@/styles/choosepro.scss";
</style>
